const ExcelJS = require("exceljs");
import { ipcMain, Notification } from "electron";
import moment from "moment";

export const getPersonExcel = (webContents) => {
  ipcMain.on("uploadChooseExcel", function(event, arg) {
    const perWorkbook = new ExcelJS.Workbook();
    const pathExcel = arg[0].path;
    perWorkbook.xlsx.readFile(pathExcel).then(function() {
      // 访问工作表
      const worksheet = perWorkbook.getWorksheet(1);
      // 遍历工作表中具有值的所有行
      var allArr = [];
      worksheet.eachRow(function(row, rowNumber) {
        const values = row.values;
        // 排查出有用的值
        if (
          typeof values[1] === "number" &&
          values[2]
          // values[3] &&
          // values[4] &&
          // values[5] &&
          // values[6]
        ) {
          allArr.push(values);
        }
      });
      // resolve(allArr)
      var obj = {
        personArr: arg,
        allArr: allArr,
      };
      webContents.send("uploadFiles", obj);
    });
  });
};

// 总表
export const getAllExcel = (webContents) => {
  ipcMain.on("uploadAllExcel", function(event, arg) {
    webContents.send("getExcelList", arg);
  });
};

export const createNewExcel = (webContents) => {
  ipcMain.on("createExcel", function(event, arg) {
    const filePath = arg.files[0].path;
    var data = arg.personAll.map((item, index) => {
      var ele = item.map((element) => {
        // && element.result
        if (typeof element === "object" && element.result) {
          element = element.result;
        }
        return element;
      });
      return ele;
    });
    const name = arg.name;
    const allWorkbook = new ExcelJS.Workbook();
    var lastnums = 0;
    var allExcelss = [];
    allWorkbook.xlsx.readFile(filePath).then(function() {
      // 访问工作表
      const worksheet1 = allWorkbook.getWorksheet(1);
      var excludeNum = [];
      var noexcludeNum = [];
      var numMachine = 0;
      // 遍历工作表中具有值的所有行
      worksheet1.eachRow(function(row, rowNumber) {
        var newArrss = [12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34];
        changeTimeValue(row, newArrss);
        const values = row.values;
        if (values[2] === name) {
          allExcelss.push({
            value: row.values,
            status: false,
            rowNumber: rowNumber,
          });
          allExcelss[numMachine].index = numMachine;
          // 找出相同的专利数据
          data.forEach((element, index) => {
            let valueTrim4 = values[4] ? values[4].trim() : "";
            let elementTrim4 = element[3] ? element[3].trim() : "";

            let valueTrim5 = values[5] ? values[5].trim() : "";
            let elementTrim5 = element[4] ? element[4].trim() : "";

            let valueTrim7 = values[7] ? values[7].trim() : "";
            let elementTrim7 = element[6] ? element[6].trim() : "";

            let valueTrim8 = values[8] ? values[8].trim() : "";
            let elementTrim8 = element[7] ? element[7].trim() : "";
            if (
              // 如果时间和客户来源一样的话
              new Date(values[3]).getTime() ===
                new Date(element[2]).getTime() && // 时间
              valueTrim4 === elementTrim4 && // 客户来源
              valueTrim5 === elementTrim5 // 客户名称
            ) {
              // 如果专利名称和专利类型相同的话
              if (
                valueTrim7 === elementTrim7 && // 专利名称
                valueTrim8 === elementTrim8 // 专利类型
              ) {
                excludeNum.push(index);
                allExcelss[numMachine].status = true;
                lastnums = rowNumber;
                row.getCell(6).value = element[5];
                row.getCell(10).value = element[9];
                row.getCell(11).value = element[10];
                /* row.getCell(11).value = element[10]
                  ? moment(element[10]).format("YYYY/MM/DD")
                  : ""; */
                row.getCell(13).value = element[12];
                row.getCell(15).value = element[14];
                row.getCell(17).value = element[16];
                row.getCell(19).value = element[18];
                row.getCell(21).value = element[20];
                row.getCell(23).value = element[22];
                row.getCell(25).value = element[24];
                row.getCell(27).value = element[26];
                row.getCell(29).value = element[28];
                row.getCell(31).value = element[30];
                row.getCell(33).value = element[32];
                row.getCell(35).value = element[34];
                row.commit();
              }
            }
          });
          numMachine = numMachine + 1;
        }
      });

      // 得出新增的没有被添加进去的值 5 7 8
      if (excludeNum.length > 0) {
        var editArr = [];
        allExcelss.forEach((ell) => {
          data.some((item) => {
            if (!ell.status) {
              if (
                (ell.value[5] === item[4] && ell.value[7] === item[6]) ||
                (ell.value[5] === item[4] && ell.value[8] === item[7]) ||
                (ell.value[7] === item[6] && ell.value[8] === item[7])
              ) {
                worksheet1.getRow(ell.rowNumber).getCell(5).value = item[4];
                worksheet1.getRow(ell.rowNumber).getCell(7).value = item[6];
                worksheet1.getRow(ell.rowNumber).getCell(8).value = item[7];
                editArr.push(ell.index);
                return true;
              }
            }
          });
        });
        data.forEach((item, index) => {
          if (
            excludeNum.indexOf(index) === -1 &&
            editArr.indexOf(index) === -1
          ) {
            // 找出新增的专利条目
            noexcludeNum.push(index);
            worksheet1.duplicateRow(lastnums, 1, true);
            var numsz = worksheet1.getRow(lastnums).getCell(1).value;
            worksheet1.getRow(lastnums + 1).getCell(1).value = numsz + 1;
            worksheet1.getRow(lastnums + 1).getCell(3).value = data[index][2];
            worksheet1.getRow(lastnums + 1).getCell(4).value = data[index][3];
            worksheet1.getRow(lastnums + 1).getCell(5).value = data[index][4];
            worksheet1.getRow(lastnums + 1).getCell(6).value = data[index][5];
            worksheet1.getRow(lastnums + 1).getCell(7).value = data[index][6];
            worksheet1.getRow(lastnums + 1).getCell(8).value = data[index][7];
            worksheet1.getRow(lastnums + 1).getCell(9).value = data[index][8];
            worksheet1.getRow(lastnums + 1).getCell(10).value = data[index][9];
            worksheet1.getRow(lastnums + 1).getCell(11).value = data[index][10];
            worksheet1.getRow(lastnums + 1).getCell(13).value = data[index][12];
            worksheet1.getRow(lastnums + 1).getCell(15).value = data[index][14];
            worksheet1.getRow(lastnums + 1).getCell(17).value = data[index][16];
            worksheet1.getRow(lastnums + 1).getCell(19).value = data[index][18];
            worksheet1.getRow(lastnums + 1).getCell(21).value = data[index][20];
            worksheet1.getRow(lastnums + 1).getCell(23).value = data[index][22];
            worksheet1.getRow(lastnums + 1).getCell(25).value = data[index][24];
            worksheet1.getRow(lastnums + 1).getCell(27).value = data[index][26];
            worksheet1.getRow(lastnums + 1).getCell(29).value = data[index][28];
            worksheet1.getRow(lastnums + 1).getCell(31).value = data[index][30];
            worksheet1.getRow(lastnums + 1).getCell(33).value = data[index][32];
            worksheet1.getRow(lastnums + 1).getCell(35).value = data[index][34];
            worksheet1.getRow(lastnums + 1).commit();
            lastnums = lastnums + 1;
          }
        });
      }
      const index = filePath.indexOf(".xlsx");
      const save = filePath.substring(0, index);
      var time = moment().format("MM-DD");
      if (filePath.indexOf(time) > -1) {
        allWorkbook.xlsx.writeFile(save + ".xlsx");
      } else {
        allWorkbook.xlsx.writeFile(save + time + ".xlsx");
      }
      console.log("成功");
      const notification = new Notification({
        title: "生成成功",
        body: "比对差异已完毕，查看生成文件" + save + time + ".xlsx",
      });
      notification.show();
      var resultData = {
        editList: excludeNum,
        addList: noexcludeNum,
      };
      webContents.send("uploadSuccess", resultData);
    });
  });
};

function formatDate(numb, format) {
  const time = new Date((numb - 1) * 24 * 3600000 + 1);
  time.setYear(time.getFullYear() - 70);
  const year = time.getFullYear() + "";
  const month = time.getMonth() + 1 + "";
  const date = time.getDate() - 1 + "";
  if (format && format.length === 1) {
    return year + format + month + format + date;
  }
  return (
    year + (month < 10 ? "0" + month : month) + (date < 10 ? "0" + date : date)
  );
}

function changeTimeValue(row, arr) {
  // moment(formatDate(row.getCell(30).value, "-")).format();
  arr.forEach((item) => {
    if (row.getCell(item).value) {
      if (row.getCell(item).type === 6) {
        row.getCell(item).value = moment(row.getCell(item).value.result).format('M月D日');
      } else {
        let numzz = row.getCell(item).value
        if (typeof numzz === 'number') {
          row.getCell(item).value = moment(formatDate(numzz, '-'), 'YYYY-M-D').format('M月D日')
        }
      }
    }
  });
}
